var mysql = require('mysql');
const path = require('path');
const request = require('request');
const fs = require('fs');
const { download } = require('wget');
var urlencode = require('urlencode');
const { URL } = require('url');
var mydb = mysql.createConnection({
    host: 'localhost',
    database: 'v7',
    //    port: 3306,
    user: 'root',
    password: 'root',
    //charset: 'UTF8_GENERAL_CI',
    debug: false
});
mydb.connect(function(err) {
    if (err) {
        console.error(err);
        throw err;
    }
});


mydb.query("select id,name,logo from t_pinjian_area_common_brand where logo like '%pinjian_dili%'",
    function(err, rst) {
        if (err) {
            console.error(err);
            throw err;
        }
        rowDataHandler(0, rst);
    });
// wget.;

mydb.end();


function rowDataHandler(startIndex, rows) {
    // console.log(rows[0].id);
    if (rows.length > 100 + startIndex) {

        for (let i = 0; i < 100; i++) {

            let row = rows[startIndex];

            startIndex++;
            const fileDir = path.resolve(__dirname, './tmp/');
            const filePath = path.resolve(fileDir, row.id + '.png');
            const url = new URL(`http://www.anluyun.com/photo/${row.name}/0.png`);
            download(url.href, __dirname + '/tmp/' + row.id + '.png').on('end', function(output) {
                console.log("download all the pics" + output);
            }).on('progress', (output, progress) => {

                // if (process == 1)
                //     console.log(output + ' 下载了 ' + progress * 100 + "%");
            }).on('error', function(err) {
                console.log(err);
            });
        }

        rowDataHandler(startIndex, rows);
    } else {

        for (let i = 0; i < rows.length - startIndex; i++) {

            let row = rows[startIndex];
            startIndex++;
            const fileDir = path.resolve(__dirname, './tmp/');
            const filePath = path.resolve(fileDir, row.id + '.png');
            const url = new URL(`http://www.anluyun.com/photo/${row.name}/0.png`);
            download(url.href, __dirname + '/tmp/' + row.id + '.png').on('end', function(output) {
                console.log("download all the pics" + output);
                // i++;
                // console.log(i);
            }).on('progress', (output, progress) => {

                // if (process == 1)
                //     console.log(output + ' 下载了 ' + progress * 100 + "%");
            }).on('error', function(err) {
                console.log(err);
            });
        }
    }
}